package handlers;

import java.net.Socket;
import java.util.ArrayList;

import common.classes.HeaderWorker;
import common.classes.SimpleServer;

public class LoadBallanserHandler extends Handler {
	ArrayList<SimpleServer> list;
	int count;

	public LoadBallanserHandler() {
		super();
		this.list = new ArrayList<SimpleServer>();
		this.count = 0;
	}

	public LoadBallanserHandler(Handler next) {
		super(next);
		this.list = new ArrayList<SimpleServer>();
		this.count = 0;
	}

	public LoadBallanserHandler(Handler next, ArrayList<String> list, int []percents) {
		super(next);
		this.list = new ArrayList<SimpleServer>();
		this.count = 0;
		for (int i = 0; i < list.size(); i++) {
			this.list.add(new SimpleServer(list.get(i), percents[i]));
		}
	}
	
	@Override
	public void parseRequest(Socket socket, HeaderWorker header, String error) {
		if (error != null) {
			super.parseRequest(socket, header, error);
			return;
		}
		for (int i = 0; i < this.list.size(); i++)
			if (this.list.get(i).canGet(this.count)) {
				list.get(i).get(socket);
				this.count++;
				return;
			}
		super.parseRequest(socket, header, "503 Service Unavailable");
	}
 
}
